<template>
  <div class="script-input">
    <div class="input">
      <el-input
        v-if="manual"
        v-model="value"
        :placeholder="props.placeholder"
        :disabled="props.disabled"
        :size="props.size"
        :clearable="props.clearable"
        @input="handleInput"
        @blur="handleBlur"
      ></el-input>
      <ac-tree
        v-else
        v-model="value"
        data-url="/system/scriptGroovy/queryTree"
        type-select="script"
        :size="props.size"
      />
    </div>
    <div class="switch">
      <ac-switch
        v-model="manual"
        @change="value = ''"
        :options="[{key: true, value: ''}, {key: false, value: ''}]"
        title="手动输入"
        size="small"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
const emit = defineEmits(['change', 'blur']);
const modelValue = defineModel();
const props = defineProps({
  placeholder: String,
  disabled: Boolean,
  size: String,
  clearable: Boolean
});

const manual = ref(true);
const value = ref('');

const handleInput = () => {
  changeValue();
};

const handleBlur = (event) => {
  emit('blur', event);
};

const changeValue = () => {
  modelValue.value = JSON.stringify({
    value: value.value,
    manual: manual.value
  });
  emit('change');
};

watch(() => manual.value, () => {
  changeValue();
});

watch(() => value.value, () => {
  changeValue();
});

onMounted(() => {
  let json = {};
  if (modelValue.value) {
    try {
      json = JSON.parse(modelValue.value);
    } catch (ignore) { /* empty */ }
  }

  manual.value = json.manual !== false;
  value.value = json.value || '';
});
</script>

<style scoped lang="scss">
.script-input {
  width: 100%;
  display: flex;
  flex-direction: row;
  .input {
    flex-grow: 1;
  }
  .switch {
    padding-left: 5px;
  }
}
</style>